import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:isolate';

import 'package:tts_server/tts.dart';

Future<void> myServer(int port, SendPort sender) async {
  ServerSocket sock = await ServerSocket.bind('0.0.0.0', port);
  sock.listen((event) async {
    List<int> data = List.empty(growable: true);
    int length = 0;

    await event.forEach((element) async {
      if (length == 0) {
        length = int.parse(utf8.decode(element.sublist(0,8)));
        if (element.length > 8) {
          data = element.sublist(8, element.length).toList(growable: true);
        }
      } else {
        data.addAll(element.toList());
      }
      
      if (data.length >= length) {
        var text1 = utf8.decode(data);
        //print(text1);
        var fileName = await textToAudio(text1);
        var file1 = File(fileName);
        var data1 = await file1.readAsBytes();
        event.write(data1);
        await event.close();
        sender.send(text1);
        await file1.delete();
      }
    });
  });
}
